package com.deepplin.mongodbmanager.function;

import java.net.UnknownHostException;

import com.deepplin.mongodbmanager.model.MongoDBSearch;
import com.deepplin.mongodbmanager.model.MongoDBSession;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;

public class MongoDBFunction {

	private static MongoDBFunction mongoFunction = null;
	
	private MongoDBFunction(){
	}
	
	/**
	 * MongoDBFunction 객체 반환
	 * @return
	 */
	public static MongoDBFunction getInstance(){
		if( mongoFunction == null ){
			mongoFunction = new MongoDBFunction();
		}
		return mongoFunction;
	}
	
	/**
	 * MongoDB의 DB 리스트 반환
	 * @param mgSession
	 * @return
	 */
	public boolean getDBList( MongoDBSession mgSession, MongoDBSearch mgSearch) {
		MongoClient mongoClient = null;
		try {
			mongoClient = new MongoClient( mgSession.getHOST(), mgSession.getPORT());
			mgSession.setMongoClient(mongoClient);			
			mgSearch.setListDB( mgSession.getMongoClient().getDatabaseNames());
			
		} catch (UnknownHostException e){
			System.out.println("알 수 없는 HOST");
			mgSession.setbCheckSession(false);
			return false;
		} catch (MongoException e2) {
			System.out.println("MongoDB 접속에 에러 발생 PORT 번호 확인 필요");
			mgSession.setbCheckSession(false);
			return false;
		}
		return true;
	}
	
	/**
	 * 해당 DB의 Collection 리스트를 반환
	 * @param mgSession
	 * @return
	 */
	public boolean getCollectionlist( MongoDBSession mgSession,  MongoDBSearch mgSearch){
		mgSearch.setListCollection( mgSession.getMongoClient().getDB( mgSearch.getStrDBName()).getCollectionNames());
		return true;
	}
		
	/**
	 * 해당 서버로 접속 처리
	 * @param mgSession
	 * @return
	 */
	public boolean connection( MongoDBSession mgSession){
		MongoClient mongoClient = null;
		try {
			mongoClient = new MongoClient( mgSession.getHOST(), mgSession.getPORT());
		} catch (UnknownHostException e) {
			mgSession.setbCheckSession(false);
			mgSession.setMongoClient(null);			
			System.out.println("#MongoDBSession.java#IP 또는 HOST 명이 잘못되었습니다#");		
			return false;
		}		
		mgSession.setMongoClient(mongoClient);
		mgSession.setbCheckSession(true);
		return true;
	}
	
	/**
	 * 접속 여부 확인
	 * @param mgSession
	 * @return
	 */
	public boolean checkConnection( MongoDBSession mgSession){
		return mgSession.isbCheckSession();
	}
	
	/**
	 * 접속 끊기
	 * @param mgSession
	 * @return
	 */
	public boolean disConnection( MongoDBSession mgSession){
		mgSession.setbCheckSession(false);
		return true;
	}
	
	/**
	 * Collection 내 문서 개수 
	 * @param mgSession
	 * @return
	 */
	public long countDocument( MongoDBSession mgSession , MongoDBSearch mgSearch){
		return mgSession.getMongoClient().getDB( mgSearch.getStrDBName()).getCollection( mgSearch.getStrCollectionName()).getCount();
	}
 
}
